package org.windey.client;

/**
 * 
 * 
 *
 */
public class WindeyClientReceiveThread extends Thread
{
	private WindeyServerConnection conn;
	private WindeyClientDataHandler wcdh;
	private WindeyClientThreadInterface wti;
	private WindeyClientStreamThread wcst;
	
	/**
	 * 
	 * @param wcdh
	 * @param wcst
	 * @param wti
	 * @param conn
	 */
	public WindeyClientReceiveThread(WindeyClientDataHandler wcdh, WindeyClientStreamThread wcst, WindeyClientThreadInterface wti, WindeyServerConnection conn)
	{
		this.conn = conn;
		this.wcdh = wcdh;
		this.wti = wti;
		this.wcst = wcst;
	}
	
	/**
	 * 
	 */
	public void run()
	{
		System.out.println("receivethread started");
		while (conn.isConnected())
		{
			if (wti.isReceiving() && !wcdh.isAlive())
			{
				try {
				wcdh.start();
				}
				catch (IllegalThreadStateException e) {
					// TODO: handle exception
				}
			}
			if (wti.isStreaming() && !wcst.isAlive())
			{
				wcst.start();
			}
			String dataLine = conn.receive();
			//System.out.println("received data : " + dataLine);
			if(dataLine.equalsIgnoreCase("EOC"))
			{
				wti.setReceiving(false);
				wti.setStreaming(false);
				conn.send("EOC") ;
			}
			else if(dataLine.equalsIgnoreCase("WindeyStartStream"))
			{
				wti.setReceiving(true);
				wti.setStreaming(true);
			}
			else
			{
				wcdh.handle(dataLine);
			}
		}
	}
}
